package com.powernode.bank.service.impl;

import com.powernode.bank.dao.AccountDao;
import com.powernode.bank.pojo.Account;
import com.powernode.bank.service.AccountService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;


@Service("accountService")
public class AccountServiceImpl implements AccountService {

    @Resource(name="accountDao")
    private AccountDao accountDao;

    // 控制事务
    @Override
    public void transfer(String from, String to, Double money) {
        // 开启事务

        // 查询转出账户的余额是否充足
        Account fromAccount = accountDao.selectByActno(from);
        if(fromAccount.getBalance()<money){
            throw new RuntimeException("金额不足！！！");
        }
        Account toAccount = accountDao.selectByActno(to);

        // 将内存中两个对象的余额先修改
        fromAccount.setBalance(fromAccount.getBalance()-money);
        toAccount.setBalance(toAccount.getBalance()+money);

        // 数据库更新
        int count = accountDao.update(fromAccount);

        // 模拟事务
        /*String s=null;
        s.toString();*/

        count+=accountDao.update(toAccount);

        if(count!=2){
            throw new RuntimeException("转账失败，请联系银行！！！");
        }

        // 提交事务

        // 回滚事务
    }
}
